package bootstrap.liftweb

import net.liftweb.common._
import net.liftweb.http._
import net.liftweb.http.S._
import net.liftweb.util._
import net.liftweb.util.Helpers._
import scala.xml._
import net.liftmodules.JQueryModule
import net.eicp.jxcontent.core.util._
import net.eicp.jxcontent.core.snippet.JXCenterSnippet

class Boot {
  
  val logger = Logger(getClass)

  //utf-8编码
  def boot {
    
    LiftRules.early.append {
      _.setCharacterEncoding("UTF-8")
    }
    
    LiftRules.useXhtmlMimeType = false
    
    //制定jquery版本
    JQueryModule.InitParam.JQuery=JQueryModule.JQuery1102
    JQueryModule.init()
    
    LiftRules.addToPackages("net.liftweb.util")

    S.addAnalyzer {
      case (Full(req), duration, log) => {
        logger.debug(("Total request time on %s: %d ms").format(req.uri, duration))
        log.foreach {
          case (stmt,duration) =>
            logger.debug("  %s in %d ms".format(stmt, duration))
        }
      }
      case _ => // we don't log for non-requests
    }
    
    //按优先级加载插件
    //bootClassName是boot所在类名
    (for ((pluginInfo, isEnabled) <- Props.props if
      //插件的格式是  JXPlugins.插件包名.优先级=是否启用，例如  JXPlugins.net.eicp.jxcontent.cms.50=true
      //查找此插件是否被配置
      (pluginInfo startsWith "JXPlugins.") && isEnabled == "true"
    ) yield {
      //获取插件优先级
      val levelString = pluginInfo.split('.').last
      val level = levelString.toString
      val bootPackageName = pluginInfo.replaceAll("JXPlugins.", "").replace("." + levelString, "")
      (bootPackageName, level.toInt)
    }).toList
    //按优先级排序
    .sortWith( _._2 > _._2 )
    .foreach{case (bootPackageName, level) => {
      logger.info(s"正在加载${bootPackageName}插件")
      val  bootClassName = bootPackageName + ".Boot"
      val bootLoader = Class.forName(bootClassName).newInstance
      import scala.language.reflectiveCalls
      bootLoader.asInstanceOf[PluginBoot].pluginLevel(PluginLevel(bootPackageName, level)).boot
    }}

    val jxSnippetDispatch = JXRules.snippetDispatch.toList
    //把snippet转发到一个centerDispatch，必须定义在其他snippet之后
    LiftRules.snippetDispatch.append {
      case snippetName if
        jxSnippetDispatch.exists{ case (snippetDispatch, _) => snippetDispatch.isDefinedAt(snippetName) } =>
        JXCenterSnippet(jxSnippetDispatch.collect{
          case (snippetDis, level) if snippetDis.isDefinedAt(snippetName) => (snippetDis(snippetName), level)
        })
    }
    
    logger.info("初始化完毕")
  
  }
  
}